package com.ziytek.web.citizen.handler;

import com.ziytek.web.citizen.constant.NumConstant;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author fenghx
 * @version v1.0
 * @className BootNettyTcpChannelInitializer
 * @descripton 功能描述
 * @date 2023/4/13 10:24
 **/
@Slf4j
@ChannelHandler.Sharable
public class ServiceChannelInitializer<SocketChannel> extends io.netty.channel.ChannelInitializer<Channel> {

    public static long READ_TIME_OUT = 60;
    public static long WRITE_TIME_OUT = 60;
    public static long ALL_TIME_OUT = 60;

    @Override
    protected void initChannel(Channel ch) {

        // 添加自定义的结束符
//        ByteBuf delimiter = Unpooled.buffer().writeBytes("\r\n".getBytes());
        //ByteBuf delimiterDa = Unpooled.buffer().writeBytes(ServerConstant.DATA_SEPARATOR_RN.getBytes());
        //ByteBuf delimiter = Unpooled.copiedBuffer(ServerConstant.DATA_SEPARATOR_END.getBytes());
        // CC0D0A的byte数组
        byte[] delimiterBytes = {-52, 13, 10};
        // 0D0A结尾的byte数组
        // byte[] delimiterBytes = {13, 10};
        ByteBuf delimiterEnd = Unpooled.wrappedBuffer(delimiterBytes);
//        先使用DelimiterBasedFrameDecoder解码，以作为分割符
        //ch.pipeline().addLast(new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, false, true, delimiterDa));
        ch.pipeline().addLast(new DelimiterBasedFrameDecoder(NumConstant.INT_DATA_LEN, false, true, delimiterEnd));

        // 添加自定义的结束符
        //ch.pipeline().addLast("framer", new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, delimiter));


        //ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(MAX_LEN));
        // 编码 解决接收数据乱码问题
        // 增加固定长度解码器
        //ch.pipeline().addLast(new FixedLengthFrameDecoder(ServerConstant.DATA_FIXED_LENGTH));
        //ch.pipeline().addLast(new FixedLengthFrameDecoder(ServerConstant.BORD_DATA_LENGTH));
        // ch.pipeline().addLast(new LineBasedFrameDecoder(1024*10));
        // 按数据长度解析数据包数据
        // ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 3, 2, 2, 0));
        //ch.pipeline().addLast(new IdleStateHandler(READ_TIME_OUT, WRITE_TIME_OUT, ALL_TIME_OUT, TimeUnit.SECONDS));
        ch.pipeline().addLast(new IdleStateHandler(READ_TIME_OUT, WRITE_TIME_OUT, ALL_TIME_OUT, TimeUnit.SECONDS));

        // 带编码
        ch.pipeline().addLast("decoder", new MyDecoder());
        // 自定义ChannelInboundHandlerAdapter
        ch.pipeline().addLast(new BootNettyChannelInboundHandlerAdapter());
    }
}